package top.dreamcenter.rss.rsssolverpluginxhs;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import top.dreamcenter.rss.common.entity.RSS;
import top.dreamcenter.rss.common.entity.RssItem;
import top.dreamcenter.rss.rsssolverprotocal.RegisterSpider;
import top.dreamcenter.rss.rsssolverprotocal.SpiderTemplate;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

@RegisterSpider
public class XhsSpider implements SpiderTemplate {

    private WebDriver driver;

    private String cookies = "";

    private boolean available = false;

    public String getRoute() {
        return "xhs";
    }

    @Override
    public String getCron() {
        return "0 * * * * ?";
    }

    public void setConfig(Hashtable<String, String> config) {
        if (config.containsKey("cookies")) cookies = config.get("cookies");
    }

    public void setDriver(WebDriver driver) {
        this.driver = driver;
    }

    public void initCookies() {
        if (cookies.equals("")) {
             throw new RuntimeException("需要cookies配置");
        } else {
            available = true;
            // 打开网页
            driver.navigate().to("https://edith.xiaohongshu.com/api/sns/web/unread_count");

            String[] kvStrs = cookies.split("; ");
            for (String kvStr : kvStrs) {
                String[] split = kvStr.split("=");
                driver.manage().addCookie(new Cookie(split[0], split[1], ".xiaohongshu.com","/", new Date(System.currentTimeMillis() + 60 * 60 * 1000)));
            }

            System.out.println(cookies);
            System.out.println(driver.getPageSource());
        }
    }

    public void caller(String key, RSS rss) {
        if (!available) return;

        String url = "https://www.xiaohongshu.com/user/profile/" + key;
        System.out.println(url);

        try {

            driver.navigate().to(url);

            System.out.println("=================" + url + "===================\n");

            // 等待元素装载成功
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
            List<WebElement> blogs = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#userPostedFeeds > section")));

            rss.setTitle(driver.findElement(By.cssSelector(".user-name")).getText());
            rss.setDescription(driver.findElement(By.cssSelector(".user-desc")).getText());
            rss.setLink(url);

            // 解析元素
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
            List<RssItem> result = rss.getItem();
            List<String> links = result.stream().map(RssItem::getLink).collect(Collectors.toList());
            for (WebElement blog : blogs) {
                System.out.println(blog);

                String title = blog.findElement(By.cssSelector("div > div > a > span")).getText();
                String content = blog.findElement(By.cssSelector("img")).getAttribute("src");
                String link = blog.findElement(By.cssSelector("div > a.cover")).getAttribute("href");
                System.err.println(link);

                // 因为无法取到时间元素，所以采用时间步进法同步最新数据，时间取截止时间
                if (!links.contains(link)) {
                    links.add(link);
                    result.add(new RssItem(
                            title, "<img src='" + content + "'/>", link, link, sdf.format(Calendar.getInstance().getTime())
                    ));
                }
            }
            System.out.println(result);
            System.out.println(rss);
        } finally {
            // 关闭浏览器
//            driver.quit();
        }
    }
}
